//
//  PPTimeOpeView.m
//  StatusBarEX
//
//  Created by Garenge on 2020/12/1.
//  Copyright © 2020 鹏鹏. All rights reserved.
//

#import "PPTimeOpeView.h"


@interface PPTimeOpeView()

@property (nonatomic, strong) NSDateFormatter *dateFormatter;

@end

@implementation PPTimeOpeView

- (void)initFormXib {
    UINib *nib = [UINib nibWithNibName:NSStringFromClass([PPTimeOpeView class]) bundle:[NSBundle mainBundle]];
    self.content = [[nib instantiateWithOwner:self options:nil] firstObject];
    self.content.frame = self.bounds;
    [self addSubview:self.content];
    
    [self.timePicker addTarget:self action:@selector(timeChanged) forControlEvents:UIControlEventValueChanged];
}
- (void)timeChanged {
    NSString *timeString = [self getFormatTimeString];
    self.showTimeLabel.text = timeString;
    if (self.timeChangdBlock != nil) {
        self.timeChangdBlock(timeString);
    }
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initFormXib];
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder {
    if (self = [super initWithCoder:coder]) {
        [self initFormXib];
    }
    return self;
}

- (NSDateFormatter *)dateFormatter {
    if (nil == _dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        _dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    }
    return _dateFormatter;
}

@synthesize timeFormat = _timeFormat;
- (NSString *)timeFormat {
    if ( nil == _timeFormat) {
        _timeFormat = @"HH:mm";
        self.dateFormatter.dateFormat = _timeFormat;
    }
    return _timeFormat;
}

/// 一旦我设置时间格式, 就刷新一遍时间文字
- (void)setTimeFormat:(NSString *)timeFormat {
    _timeFormat = timeFormat;
    self.dateFormatter.dateFormat = timeFormat;
    [self timeChanged];
}

/// 刷新时间的时候是否需要刷新时间格式
- (NSString *)getFormatTimeString {

    NSDate *theDate = self.timePicker.date;
    NSLog(@"%@",[theDate descriptionWithLocale:[NSLocale currentLocale]]);

    NSString *preFormat = self.dateFormatter.dateFormat;

    // 不管24还是12 , 都要先获取准确的时间
    self.dateFormatter.dateFormat = @"HH:mm";
    NSString *timeString = [self.dateFormatter stringFromDate:theDate];
    NSLog(@"按照24小时格式获取的时间: %@", timeString);
    if ([preFormat isEqualToString:@"HH:mm"]) {
        // 24小时
    } else {
        // 12小时制
        self.dateFormatter.dateFormat = @"h:mm";
        NSString *tmp12String = [self.dateFormatter stringFromDate:theDate];
        NSLog(@"按照12小时格式获取的时间: %@", tmp12String);
        if ([timeString compare:@"11:59"] == NSOrderedDescending) {
            // 下午
            timeString = [NSString stringWithFormat:@"下午%@", tmp12String];
        } else {
            // 上午
            timeString = [NSString stringWithFormat:@"上午%@", tmp12String];
        }
        NSLog(@"12小时制时间: %@", timeString);
    }

    self.dateFormatter.dateFormat = preFormat;
    return timeString;
}

@end
